<template>
  <div style="padding: 15px 10px;">
    <a-row type="flex" justify="space-between">
      <a-col :span="24">
        <a-button type="primary" @click="init">刷新</a-button>
        <a-button type="primary" @click="cwRotation">逆时针旋转90°</a-button>
        <a-button type="primary" @click="showCode">复制代码至剪切板</a-button>
        <a-button type="primary" @click="download">下载图片</a-button>
        <a-tag 
          v-if="hasSelectedNode"
          color="blue" 
          @close="selectedNodeId = ''"
          closable
        >
          {{ selectedNodeValue }}
        </a-tag>
      </a-col>
    </a-row>  
    <a-row type="flex" :gutter="24" justify="space-between">
      <a-col :span="hasSelectedNode ? 14 : 24">
        <div :style="chartWrapperStyle" ref="chartWrapper"></div>
      </a-col>
      <a-col v-if="hasSelectedNode" :span="10">
        <flow-chart-line-list :target-node-id="selectedNodeId" :is-null-val-does-not-query="true"/>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="es6">
module.exports = asyncRequire([
  'alias!@PAGE/components/flowchart',
  'alias!@PAGE/components/localNodes',
  'mermaid',
  'jquery'
], (generateGraphDefinition, NodeAPI, mermaid, jQuery, resolve, reject) => {
  resolve({
    name: 'FlowCardView',
    components: {
      FlowChartLineList: load('./FlowChartLineList')
    },
    props: {
      needHide: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        layout: 'TB',
        nodes: NodeAPI.findAll().nodes,
        selectedNodeId: '',
        selectedNodeValue: '',
        graphDefinition: 'graphDefinition',
      }
    },
    mounted () {
      this.init();
    },
    computed: {
      hasSelectedNode () {
        return this.selectedNodeId !== '';
      },

      chartWrapperStyle () {
        let height = this.$store.getters['screen/screenInfo'].height - 360;
        let styleObj;

        if(this.hasSelectedNode) {
          styleObj = {
            'text-align': 'center',
            'overflow': 'scroll',
            'height': height + 'px',
            'min-height': height + 'px',
            'max-height': height + 'px'
          };
        } 

        styleObj = {
          'text-align': 'center'
        };

        if(this.needHide) {
          styleObj.display = 'none';
        }

        return styleObj;
      }
    },
    watch: {
      hasSelectedNode(to, from) {
        if(to) {
          jQuery(document).scrollTop(jQuery(document).scrollTop() * -1);
        }
      }
    },
    methods: {
      init () {
        const globalCallbackId = "flowChartCallback"
        window[globalCallbackId] = (event) => {
          this.onClick(event);
        }

        let allData = NodeAPI.findAll();
        let nodes = allData.nodes;
        let lines = allData.lines;

        this.initFlowChart(this.$refs.chartWrapper, null, nodes, lines, globalCallbackId);
      },

      initFlowChart(el, rootId, nodes, lines, globalCallbackId) {
        el.innerHTML = '';
        let graphDefinition = generateGraphDefinition(rootId, nodes, lines, globalCallbackId, this.layout);
        this.graphDefinition = graphDefinition;
        // console.log(graphDefinition);

        mermaid.initialize({
            securityLevel: 'loose'
        });

        var graph = mermaid.render('graphDiv-1', graphDefinition, (svgCode, bindFunctions) => {
            el.innerHTML = svgCode;
            bindFunctions(el);
        }, el);
      },

      cwRotation () {
        let layouts = ['TB', 'LR', 'BT', 'RL'];
        let nextIndex = (layouts.indexOf(this.layout) + 1) % 4;
        this.layout = layouts[nextIndex];
        this.init();
      },

      copyText (text){
        var oInput = document.createElement('textarea');
        oInput.innerHTML = text;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象
        document.execCommand("Copy"); // 执行浏览器复制命令
        oInput.className = 'oInput';
        oInput.style.display='none';
        oInput.remove();
      },

      showCode () {
        let tArr = this.graphDefinition.split('\r\n');
        let endIndex = tArr.findIndex(item => item.trim().indexOf('click') >= 0);
        endIndex = endIndex > 0 ? endIndex : tArr.length;
        this.copyText(tArr.slice(0, endIndex).join('\r\n'));
        this.$message.success('流程图描述文本复制成功');
      },

      covertSVG2Image (node, name, width, height, type) {
        let serializer = new XMLSerializer();
        let source = '<?xml version="1.0" standalone="no"?>\r\n' + serializer.serializeToString(node);
        let image = new Image();
        image.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(source);
        let canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        let context = canvas.getContext('2d');
        context.fillStyle = '#fff';
        context.fillRect(0, 0, 10000, 10000);
        image.onload = function () {
          context.drawImage(image, 0, 0)
          let a = document.createElement('a');
          a.download = `${name}.${type}`;
          a.href = canvas.toDataURL(`image/${type}`);
          a.click();
        }
      },

      download () {
        let svgEle = jQuery('#graphDiv-1');
        this.covertSVG2Image(svgEle.get(0), '流程图', svgEle.width(), svgEle.height(), 'jpeg');
      },

      onClick (nodeId) {
        this.selectedNodeId = nodeId;
        this.selectedNodeValue = this.nodes.find(node => node.id === nodeId).name;
      }
    }
  });
});
</script>

<style>
  .mermaidTooltip {
    position: absolute;
    margin-left: 10px;
    background-color: #FFF;
    border: 1px solid rgb(131, 122, 122);
    border-radius: 5px;
    z-index: 10;
  }
</style>

<style scoped>
  .task-group{
    margin: 0 48px;
  }
</style>
